<template>
  <div class="order-container">
    <div class="header">
      <a
        href="javascript:void(0)"
        @click="$router.push({ name: 'PersonalCenter' })"
        class="back-button"
      >
        <img src="./me-img/back.png" alt="返回" width="40%" height="100%" />
      </a>
      <img src="./me-img/logo.png" alt="logo" class="logo" />
    </div>

    <div class="body">
      <div class="tabs">
        <div
          v-for="tab in tabs"
          :key="tab.id"
          :class="['tab', { active: activeTab === tab.id }]"
          @click="activeTab = tab.id"
        >
          {{ tab.name }}
        </div>
      </div>

      <div class="order-list">
        <div v-for="order in filteredOrders" :key="order.id">
          <div class="order-item" :class="[order.status]">
            <img :src="order.image" alt="商品图片" class="product-image" />
            <div class="product-info">
              <h4 class="product-name">{{ order.name }}</h4>
              <p class="product-price">单价：{{ order.price }}￥</p>
              <p class="product-quantity">数量: {{ order.quantity }}</p>
              <p class="product-specs">商品详情：{{ order.specs }}</p>
              <p class="product-allprice">
                总计:{{ (order.price * order.quantity).toFixed(2) }}￥
              </p>
            </div>

            <div class="action-buttons">
              <button
                v-if="order.status === 'pendingPayment'"
                class="cancel-btn"
                @click="cancelOrder(order.id)"
              >
                放弃订单
              </button>
              <button
                v-if="order.status === 'pendingPayment'"
                class="primary-btn"
                @click="confirmOrder(order.id)"
              >
                确认订单
              </button>

              <router-link
                :to="{
                  name: 'evaluation',
                  query: {
                    product: JSON.stringify(order),
                  },
                }"
                v-if="order.status === 'pendingReview'"
                class="comment-btn"
              >
                去评价
              </router-link>

              <button
                v-if="order.status === 'pendingDelivery'"
                class="where-btn"
                @click="viewLogistics(order.id)"
              >
                查看物流
              </button>
              <button
                v-if="order.status === 'pendingDelivery'"
                class="delivery-btn"
                @click="confirmReceipt(order.id)"
              >
                确认收货
              </button>

              <button
                v-if="order.status === 'afterSale'"
                class="change-btn"
                @click="change(order)"
              >
                退货换货
              </button>

              <div
                v-if="order.status === 'returning'"
                class="status-badge returning"
              >
                退货中
                <button
                  class="complete-btn"
                  @click="completeAfterSale(order.id)"
                >
                  完成售后
                </button>
              </div>
              <div
                v-if="order.status === 'exchanging'"
                class="status-badge exchanging"
              >
                换货中
                <button
                  class="complete-btn"
                  @click="completeAfterSale(order.id)"
                >
                  完成售后
                </button>
              </div>

              <button
                v-if="order.status === 'afterSale'"
                class="service-btn"
                @click="service(order.id)"
              >
                平台客服
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import orderData from "./me.json";

export default {
  name: "OrderList",
  data() {
    return {
      activeTab: this.$route.query.tab || "pendingPayment", // 从路由参数初始化
      tabs: [
        { id: "pendingPayment", name: "待付款" },
        { id: "pendingReview", name: "待评价" },
        { id: "pendingDelivery", name: "待收货" },
        { id: "afterSale", name: "退换售后" },
      ],
      orders:
        JSON.parse(localStorage.getItem("orderList")) || orderData.products,
    };
  },
  watch: {
    "$route.query.tab"(newTab) {
      this.orders =
        JSON.parse(localStorage.getItem("orderList")) || orderData.products;
    },
  },

  created() {
    this.loadOrders();
    window.addEventListener("storage", this.handleStorageChange);
  },
  beforeDestroy() {
    window.removeEventListener("storage", this.handleStorageChange);
  },
  methods: {
    loadOrders() {
      const localData = localStorage.getItem("orderList");

      if (!localData) {
        // 如果没有本地数据，则使用 me.json 初始化，并写入 localStorage
        this.orders = [...orderData.products];
        localStorage.setItem("orderList", JSON.stringify(this.orders));
      } else {
        this.orders = JSON.parse(localData);
      }
    },
    handleStorageChange(event) {
      if (event.key === "orderList") {
        this.loadOrders();
      }
    },
    viewLogistics(orderId) {
      this.$router.push({
        name: "Logistics",
        query: { orderId: orderId },
      });
    },
    change(order) {
      this.$router.push({
        name: "change",
        query: {
          orderId: order.id,
          image: order.image,
          name: order.name,
          price: order.price,
          quantity: order.quantity,
          status: order.status,
          specs: order.specs,
          _t: Date.now(),
        },
      });
    },

    completeAfterSale(orderId) {
      const orderList = JSON.parse(localStorage.getItem("orderList") || []);
      const orderIndex = orderList.findIndex((item) => item.id === orderId);
      if (orderIndex !== -1) {
        orderList[orderIndex].status = "afterSaleCompleted";
        localStorage.setItem("orderList", JSON.stringify(orderList));
        this.orders = orderList; // 更新本地数据
      }
    },
    service(orderId) {
      this.$router.push({
        name: "service",
        query: { orderId: orderId },
      });
    },
    confirmReceipt(orderId) {
      const orderIndex = this.orders.findIndex((item) => item.id == orderId);
      if (orderIndex !== -1) {
        this.orders[orderIndex].status = "pendingReview";
        localStorage.setItem("orderList", JSON.stringify(this.orders));

        this.$router.push({
          name: "OrderList",
          query: { tab: "pendingReview" },
        });
      }
    },

    cancelOrder(orderId) {
      if (confirm("确定要放弃这个订单吗？")) {
        const orderList = JSON.parse(localStorage.getItem("orderList") || "[]");
        const updatedOrders = orderList.filter((item) => item.id !== orderId);
        localStorage.setItem("orderList", JSON.stringify(updatedOrders));
        this.orders = updatedOrders;
      }
    },

    confirmOrder(orderId) {
      const orderList = JSON.parse(localStorage.getItem("orderList") || "[]");
      const orderIndex = orderList.findIndex((item) => item.id === orderId);

      if (orderIndex !== -1) {
        orderList[orderIndex].status = "pendingDelivery";
        orderList[orderIndex].number = this.generateTrackingNumber();
        orderList[orderIndex].transport = "运输中";

        localStorage.setItem("orderList", JSON.stringify(orderList));
        this.orders = orderList;

        // 跳转到待收货页面
        this.$router.push({
          name: "OrderList",
          query: { tab: "pendingDelivery" },
        });
      }
    },

    generateTrackingNumber() {
      return "SF" + Math.floor(1000000000 + Math.random() * 9000000000);
    },
  },

  computed: {
    filteredOrders() {
      return this.orders.filter((order) => {
        if (this.activeTab === "afterSale") {
          return [
            "afterSale",
            "returning",
            "exchanging",
            "afterSaleCompleted",
          ].includes(order.status);
        }
        return order.status === this.activeTab;
      });
    },
  },
  watch: {
    // 监听路由变化，更新 activeTab
    "$route.query.tab"(newTab) {
      if (newTab) {
        this.activeTab = newTab;
        this.loadOrders();
      }
    },
  },
};
</script>

<style scoped>
.status-badge {
  padding: 5px 10px;
  border-radius: 4px;
  font-size: 14px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.status-badge.returning {
  background-color: #fff2f0;
  color: #f5222d;
}

.status-badge.exchanging {
  background-color: #f6ffed;
  color: #52c41a;
}

.complete-btn {
  padding: 2px 8px;
  background-color: #d9c596;
  border: none;
  border-radius: 3px;
  font-size: 12px;
  cursor: pointer;
}
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
}

/* 保持原有样式不变 */
.order-container {
  min-height: 100vh;
  background-color: #ffffff;
  min-width: 1000px; /* 添加最小宽度防止布局压缩 */
  overflow-x: auto; /* 允许横向滚动 */
}

.header {
  background-color: #f4efd2;
  height: 50px;
  align-items: center; /* 保持垂直居中 */
  box-shadow: #bdbbb7 0px 2px 8px;
  padding: 2px 0px;
}

.header,
.body {
  width: 60%;
  margin: 0px auto;
  overflow: hidden;
  display: flex;
}

.body {
  margin: 30px auto;
  height: 700px;
  background-color: #ffffff;
}

.logo {
  width: 10%;
  height: auto;
  margin-left: auto; /* 关键：将 logo 推到最右侧 */
}

.back-button {
  color: #333;
  display: flex;
  width: 10%;
  height: 100%;
  text-decoration: none;
  line-height: 40px; /* 文字垂直居中 */
  overflow: hidden; /* 防止内容溢出 */
}

.tabs {
  width: 10%;
  background-color: #f4efd2;
  margin: 0px 20px 0px 0px;
  box-shadow: #bdbbb7 0px 0px 5px;
  border-radius: 10px;
  display: flex;
  flex-direction: column; /* 垂直排列 */
  justify-content: center; /* 垂直方向居中 */
  align-items: center; /* 水平方向居中 */
  border-bottom: 1px solid #f0f0f0;
}

.tab {
  flex: 1; /* 元素在弹性容器中会占据剩余的所有可用空间 */
  margin: 20px;
  font-size: 15px;
  display: flex;
  justify-content: center; /* 垂直方向居中 */
  align-items: center; /* 水平方向居中 */
  background-color: #ffffff;
  border: 1px solid rgb(212, 211, 211);
  width: 35%;
  padding: 15px 0;
  color: black;
  border-radius: 5px;
  writing-mode: vertical-rl; /* 垂直排列文字 */
}

.tab.active {
  background-color: #d9c596;
  box-shadow: #bdbbb7 0px 0px 5px;
}

.order-list {
  width: 90%;
  box-shadow: #bdbbb7 0px 0px 5px;
  background-color: #f4efd2;
  padding: 20px 30px;
  overflow-y: auto; /* 垂直滚动 */
}

.order-item {
  width: 100%;
  height: 25%;
  padding: 15px;
  background-color: white;
  border-radius: 8px;
  display: flex;
  box-shadow: #bdbbb7 0px 0px 3px;
  margin: 10px 0px;
}

.product-image {
  width: 15%;
  height: 100%;
  border-radius: 5px;
  margin: 0px 15px;
}

.product-info {
  width: 55%;
  margin: 0px 15px;
  background-color: #f4efd2;
  padding: 0px 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  border-radius: 5px;
}

/* 待评价样式 */
.product-info.pendingReview {
  background-color: #e8f4fd;
}

/* 待收货样式 */
.product-info.pendingDelivery {
  background-color: #f0f8e8;
}

/* 退换售后样式 */
.product-info.afterSale {
  background-color: #fde8e8;
}

.product-specs {
  overflow-y: auto; /* 垂直滚动 */
}

.product-allprice {
  font-size: 25px;
  margin-top: 5px;
  color: rgb(237, 129, 51);
}

p {
  font-size: 14px;
}
.action-buttons {
  width: 20%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.cancel-btn,
.primary-btn,
.comment-btn,
.delivery-btn,
.where-btn,
.change-btn,
.merchatnt-btn,
.service-btn {
  width: 80%;
  height: 30%;
  border-radius: 5px;
  font-size: 16px;
  border: none;
  box-shadow: #bdbbb7 0px 0px 3px;
}

.comment-btn {
  color: black;
  text-decoration: none;
  text-align: center;
  padding: 5px 0 0 0;
}

.comment-btn,
.cancel-btn,
.where-btn,
.change-btn,
.merchatnt-btn {
  background-color: #d9c596;
}

.primary-btn,
.service-btn,
.delivery-btn {
  background-color: rgb(237, 129, 51);
}
</style>
